/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import entities.Contest;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.User;
import java.util.ArrayList;
import java.util.List;
import entities.Problem;
import entities.Submission;

/**
 *
 * @author sbaldrich
 */
public class ContestJpaController {

    public ContestJpaController()
    {
        emf = Persistence.createEntityManagerFactory("CMalphaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    public void create(Contest contest)
    {
        if (contest.getUserList() == null)
        {
            contest.setUserList(new ArrayList<User>());
        }
        if (contest.getProblemList() == null)
        {
            contest.setProblemList(new ArrayList<Problem>());
        }
        if (contest.getSubmissionList() == null)
        {
            contest.setSubmissionList(new ArrayList<Submission>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            List<User> attachedUserList = new ArrayList<User>();
            for (User userListUserToAttach : contest.getUserList())
            {
                userListUserToAttach = em.getReference(userListUserToAttach.getClass(), userListUserToAttach.getIdUser());
                attachedUserList.add(userListUserToAttach);
            }
            contest.setUserList(attachedUserList);
            List<Problem> attachedProblemList = new ArrayList<Problem>();
            for (Problem problemListProblemToAttach : contest.getProblemList())
            {
                problemListProblemToAttach = em.getReference(problemListProblemToAttach.getClass(), problemListProblemToAttach.getIdProblem());
                attachedProblemList.add(problemListProblemToAttach);
            }
            contest.setProblemList(attachedProblemList);
            List<Submission> attachedSubmissionList = new ArrayList<Submission>();
            for (Submission submissionListSubmissionToAttach : contest.getSubmissionList())
            {
                submissionListSubmissionToAttach = em.getReference(submissionListSubmissionToAttach.getClass(), submissionListSubmissionToAttach.getIdSubmission());
                attachedSubmissionList.add(submissionListSubmissionToAttach);
            }
            contest.setSubmissionList(attachedSubmissionList);
            em.persist(contest);
            for (User userListUser : contest.getUserList())
            {
                userListUser.getContestList().add(contest);
                userListUser = em.merge(userListUser);
            }
            for (Problem problemListProblem : contest.getProblemList())
            {
                Contest oldContestOfProblemListProblem = problemListProblem.getContest();
                problemListProblem.setContest(contest);
                problemListProblem = em.merge(problemListProblem);
                if (oldContestOfProblemListProblem != null)
                {
                    oldContestOfProblemListProblem.getProblemList().remove(problemListProblem);
                    oldContestOfProblemListProblem = em.merge(oldContestOfProblemListProblem);
                }
            }
            for (Submission submissionListSubmission : contest.getSubmissionList())
            {
                Contest oldContestOfSubmissionListSubmission = submissionListSubmission.getContest();
                submissionListSubmission.setContest(contest);
                submissionListSubmission = em.merge(submissionListSubmission);
                if (oldContestOfSubmissionListSubmission != null)
                {
                    oldContestOfSubmissionListSubmission.getSubmissionList().remove(submissionListSubmission);
                    oldContestOfSubmissionListSubmission = em.merge(oldContestOfSubmissionListSubmission);
                }
            }
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void edit(Contest contest) throws IllegalOrphanException, NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Contest persistentContest = em.find(Contest.class, contest.getIdContest());
            List<User> userListOld = persistentContest.getUserList();
            List<User> userListNew = contest.getUserList();
            List<Problem> problemListOld = persistentContest.getProblemList();
            List<Problem> problemListNew = contest.getProblemList();
            List<Submission> submissionListOld = persistentContest.getSubmissionList();
            List<Submission> submissionListNew = contest.getSubmissionList();
            List<String> illegalOrphanMessages = null;
            for (Problem problemListOldProblem : problemListOld)
            {
                if (!problemListNew.contains(problemListOldProblem))
                {
                    if (illegalOrphanMessages == null)
                    {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Problem " + problemListOldProblem + " since its contest field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<User> attachedUserListNew = new ArrayList<User>();
            for (User userListNewUserToAttach : userListNew)
            {
                userListNewUserToAttach = em.getReference(userListNewUserToAttach.getClass(), userListNewUserToAttach.getIdUser());
                attachedUserListNew.add(userListNewUserToAttach);
            }
            userListNew = attachedUserListNew;
            contest.setUserList(userListNew);
            List<Problem> attachedProblemListNew = new ArrayList<Problem>();
            for (Problem problemListNewProblemToAttach : problemListNew)
            {
                problemListNewProblemToAttach = em.getReference(problemListNewProblemToAttach.getClass(), problemListNewProblemToAttach.getIdProblem());
                attachedProblemListNew.add(problemListNewProblemToAttach);
            }
            problemListNew = attachedProblemListNew;
            contest.setProblemList(problemListNew);
            List<Submission> attachedSubmissionListNew = new ArrayList<Submission>();
            for (Submission submissionListNewSubmissionToAttach : submissionListNew)
            {
                submissionListNewSubmissionToAttach = em.getReference(submissionListNewSubmissionToAttach.getClass(), submissionListNewSubmissionToAttach.getIdSubmission());
                attachedSubmissionListNew.add(submissionListNewSubmissionToAttach);
            }
            submissionListNew = attachedSubmissionListNew;
            contest.setSubmissionList(submissionListNew);
            contest = em.merge(contest);
            for (User userListOldUser : userListOld)
            {
                if (!userListNew.contains(userListOldUser))
                {
                    userListOldUser.getContestList().remove(contest);
                    userListOldUser = em.merge(userListOldUser);
                }
            }
            for (User userListNewUser : userListNew)
            {
                if (!userListOld.contains(userListNewUser))
                {
                    userListNewUser.getContestList().add(contest);
                    userListNewUser = em.merge(userListNewUser);
                }
            }
            for (Problem problemListNewProblem : problemListNew)
            {
                if (!problemListOld.contains(problemListNewProblem))
                {
                    Contest oldContestOfProblemListNewProblem = problemListNewProblem.getContest();
                    problemListNewProblem.setContest(contest);
                    problemListNewProblem = em.merge(problemListNewProblem);
                    if (oldContestOfProblemListNewProblem != null && !oldContestOfProblemListNewProblem.equals(contest))
                    {
                        oldContestOfProblemListNewProblem.getProblemList().remove(problemListNewProblem);
                        oldContestOfProblemListNewProblem = em.merge(oldContestOfProblemListNewProblem);
                    }
                }
            }
            for (Submission submissionListOldSubmission : submissionListOld)
            {
                if (!submissionListNew.contains(submissionListOldSubmission))
                {
                    submissionListOldSubmission.setContest(null);
                    submissionListOldSubmission = em.merge(submissionListOldSubmission);
                }
            }
            for (Submission submissionListNewSubmission : submissionListNew)
            {
                if (!submissionListOld.contains(submissionListNewSubmission))
                {
                    Contest oldContestOfSubmissionListNewSubmission = submissionListNewSubmission.getContest();
                    submissionListNewSubmission.setContest(contest);
                    submissionListNewSubmission = em.merge(submissionListNewSubmission);
                    if (oldContestOfSubmissionListNewSubmission != null && !oldContestOfSubmissionListNewSubmission.equals(contest))
                    {
                        oldContestOfSubmissionListNewSubmission.getSubmissionList().remove(submissionListNewSubmission);
                        oldContestOfSubmissionListNewSubmission = em.merge(oldContestOfSubmissionListNewSubmission);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = contest.getIdContest();
                if (findContest(id) == null)
                {
                    throw new NonexistentEntityException("The contest with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Contest contest;
            try
            {
                contest = em.getReference(Contest.class, id);
                contest.getIdContest();
            } catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The contest with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Problem> problemListOrphanCheck = contest.getProblemList();
            for (Problem problemListOrphanCheckProblem : problemListOrphanCheck)
            {
                if (illegalOrphanMessages == null)
                {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Contest (" + contest + ") cannot be destroyed since the Problem " + problemListOrphanCheckProblem + " in its problemList field has a non-nullable contest field.");
            }
            if (illegalOrphanMessages != null)
            {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<User> userList = contest.getUserList();
            for (User userListUser : userList)
            {
                userListUser.getContestList().remove(contest);
                userListUser = em.merge(userListUser);
            }
            List<Submission> submissionList = contest.getSubmissionList();
            for (Submission submissionListSubmission : submissionList)
            {
                submissionListSubmission.setContest(null);
                submissionListSubmission = em.merge(submissionListSubmission);
            }
            em.remove(contest);
            em.getTransaction().commit();
        } finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    public List<Contest> findContestEntities()
    {
        return findContestEntities(true, -1, -1);
    }

    public List<Contest> findContestEntities(int maxResults, int firstResult)
    {
        return findContestEntities(false, maxResults, firstResult);
    }

    private List<Contest> findContestEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Contest.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally
        {
            em.close();
        }
    }

    public Contest findContest(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Contest.class, id);
        } finally
        {
            em.close();
        }
    }
    public Contest findContest(String contestCode)
    {
        EntityManager em = getEntityManager();
        try
        {
            Query q = em.createNamedQuery("Contest.findByContestCode");
            q.setParameter("contestCode", contestCode);
            return (Contest)q.getSingleResult();
        } finally
        {
            em.close();
        }
    }

    public int getContestCount()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Contest> rt = cq.from(Contest.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally
        {
            em.close();
        }
    }

}
